package com.ruicar.afs.cloud.basic.common.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.dispatch.contract.CmsInterfaceFeign;
import com.ruicar.afs.cloud.basic.common.condition.PrepaymentRecordQueryCondition;
import com.ruicar.afs.cloud.basic.common.condition.QueryCustInfoMultipleCondition;
import com.ruicar.afs.cloud.basic.common.entity.BasicBankCard;
import com.ruicar.afs.cloud.basic.common.entity.BasicContractCustRelation;
import com.ruicar.afs.cloud.basic.common.entity.BasicCustBaseInfo;
import com.ruicar.afs.cloud.basic.common.service.BasicBankCardService;
import com.ruicar.afs.cloud.basic.common.service.BasicContractCustRelationService;
import com.ruicar.afs.cloud.basic.common.service.BasicCustBaseInfoService;
import com.ruicar.afs.cloud.common.config.ContractFeginConfig;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.BankCardVo;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.BankListVo;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractFeginParamEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.VerStatusEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import com.ruicar.afs.cloud.manage.api.dto.PrepaymentRecordDto;
import com.ruicar.afs.cloud.manage.api.feign.cust.CustChangeFeign;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 还款银行卡数据
 */
@Slf4j
@RestController
@RequestMapping("/bankCard")
@AllArgsConstructor
public class BasicBankCardController {

    private final BasicBankCardService basicBankCardService;
    private final BasicCustBaseInfoService basicCustBaseInfoService;
    private final CustChangeFeign custChangeFeign;
    private final BasicContractCustRelationService basicContractCustRelationService;
    private final CmsInterfaceFeign cmsInterfaceFeign;
    private final ContractFeginConfig contractFeginConfig;

    @ApiOperation(value = "还款银行卡号查询接口")
    @PostMapping("/repaymentBankCard")
    public IResponse<BankListVo> repaymentBankCard(@RequestParam(value="certNo",required = false) String certNo,
                                                            @RequestParam(value="contractNo",required = false) String contractNo){
        BankListVo cd = new BankListVo();
        if((EmptyUtils.isEmpty(certNo)||"null".equals(certNo)) && (EmptyUtils.isEmpty(contractNo)||"null".equals(contractNo))){
            log.error("--------------------------证件号、合同号不可同时为空，直接返回空结果！！！--------------------------");
            return IResponse.fail("错误：参数不能为空。");
        }

        QueryCustInfoMultipleCondition condition = new QueryCustInfoMultipleCondition();
        //如果身份证和合同号码同时传入，则只使用身份证号码查询
        if((EmptyUtils.isEmpty(certNo)||"null".equals(certNo))&&(EmptyUtils.isNotEmpty(contractNo)||!"null".equals(contractNo))){
            condition.setContractNo(contractNo);
        }else{
            condition.setCertNo(certNo);
        }
        List custInfos = basicCustBaseInfoService.findByCustInfo(condition);

        List<BasicContractCustRelation> basicContractCustRelations = JSON.parseArray(JSON.toJSONString(custInfos), BasicContractCustRelation.class);
        List<String> str = new ArrayList<>();
        for (BasicContractCustRelation info : basicContractCustRelations){
            str.add(info.getContractNo());
        }

        List<BankCardVo> bankCards = new ArrayList<>();
        Integer count = 0;
        if(EmptyUtils.isNotEmpty(str)){
            List<BasicBankCard> basicBankCard = basicBankCardService.list(Wrappers.<BasicBankCard>lambdaQuery().in(BasicBankCard::getContractNo, str));
            List<BankCardVo> bankCardVos = JSON.parseArray(JSON.toJSONString(basicBankCard), BankCardVo.class);
            Map<String, List<DicDataDto>> listMap = DicHelper.getDicMaps("bankCode");
            List<DicDataDto> bankCode = listMap.get("bankCode");
            for(BankCardVo vo : bankCardVos){
                for(DicDataDto dic : bankCode){
                    if(vo.getBankCode().equals(dic.getValue())){
                        vo.setBankCode(dic.getTitle());
                    }
                }
            }

            bankCards.addAll(bankCardVos);
        }else{
            log.error("--------------------------证件号码为：{}，合同号为：{}，在贷后合同没有查询到客户信息--------------------------",certNo,contractNo);
        }

        //贷前数据
        Map map = new HashMap();
        map.put(AfsEnumUtil.key(ContractFeginParamEnum.CASE_CLIENT_SECRET),contractFeginConfig.getCaseClientSecret());
        map.put(AfsEnumUtil.key(ContractFeginParamEnum.CASE_CLIENT_ID),contractFeginConfig.getCaseClientId());
        map.put(AfsEnumUtil.key(ContractFeginParamEnum.CONTENT_TYPE), MediaType.APPLICATION_JSON_VALUE);
        IResponse<BankListVo> response = cmsInterfaceFeign.getBankNumByCertNoOrApplyNo(contractNo, certNo, map);
        if(CommonConstants.SUCCESS.equals(response.getCode())&&EmptyUtils.isNotEmpty(response.getData().getBankCards())&&response.getData().getBankCards().size()>0){
            bankCards.addAll(response.getData().getBankCards());
            count = count+response.getData().getCount();
        }

        if(EmptyUtils.isEmpty(bankCards)&&count==0){
            log.info("--------------------------证件号码为：{}，合同号为：{}，没有查询到任何数据，直接返回空结果--------------------------",certNo,contractNo);
            cd.setCount(0);
            cd.setBankCards(new ArrayList<>());
        }else{
            cd.setCount(bankCards.size()+count);
            cd.setBankCards(bankCards);
        }
        return IResponse.success(cd);
    }

    @PostMapping(value = "/bankCardChangeStatus")
    @ApiOperation(value = "还款银行卡变更审批状态查询")
    public IResponse<List<PrepaymentRecordDto>> bankCardChangeStatus(@RequestBody PrepaymentRecordQueryCondition condition){
        if (EmptyUtils.isEmpty(condition.getContractNo()) && EmptyUtils.isEmpty(condition.getCertNo())){
            return IResponse.fail("证件号或合同号，必须要传值其中的一项");
        }

        List<String> contractNoList = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(condition.getCertNo())){
            List<BasicCustBaseInfo> custPersonalDetails = basicCustBaseInfoService.list(Wrappers.<BasicCustBaseInfo>query().lambda()
                    .eq(BasicCustBaseInfo::getCertNo,condition.getCertNo())
            );
            if (EmptyUtils.isNotEmpty(custPersonalDetails)){
                List<String> custNos = custPersonalDetails.stream().map(BasicCustBaseInfo::getCustNo).collect(Collectors.toList());
                List<BasicContractCustRelation> relationList = basicContractCustRelationService.list(Wrappers.<BasicContractCustRelation>query().lambda()
                        .in(BasicContractCustRelation::getCustNo,custNos)
                        .eq(BasicContractCustRelation::getCustRole, PersonRoleTypeEnum.MAIN_PERSON)
                );
                if (EmptyUtils.isNotEmpty(relationList)){
                    relationList.forEach(relation -> {
                        contractNoList.add(relation.getContractNo());
                    });
                }
            }
        }
        if (EmptyUtils.isEmpty(condition.getCertNo())&&EmptyUtils.isNotEmpty(condition.getContractNo())){
            contractNoList.add(condition.getContractNo());
        }
        String contractNos = "";
        if (EmptyUtils.isNotEmpty(contractNoList)){
            contractNos = StringUtils.join(contractNoList.toArray(),",");
        }
        return custChangeFeign.bankCardChangeStatus(contractNos);
    }

    @PostMapping(value = "/getBankCardInfo")
    @ApiOperation(value = "还款银行卡查询")
    public IResponse getBankCardInfo(@RequestParam(value="contractNo",required = false) String contractNo){
        List<BasicBankCard> list = basicBankCardService.list(Wrappers.<BasicBankCard>lambdaQuery().
                eq(BasicBankCard::getContractNo, contractNo).eq( BasicBankCard::getVerStatus, VerStatusEnum.alreadySign));
        Assert.isTrue(!EmptyUtils.isEmpty(list),"已签约的银行卡不存在");
        return  IResponse.success(list.get(0));

    }
}
